/**
 * @brief 4G DTU 应用程序
 * @version 1.0
 * @date 2018-2-24
 * @author 宋炜
*/

#include <unistd.h>

#include <iostream>
#include <thread>
#include <atomic>

#include "defines.hpp"
#include "dtu.hpp"
#include "sys_var.hpp"

void on_abort( int id )
{
    	__show_line_2();
}

void on_sigsegv( int id )
{
	__show_line_2();
}

int main( int argc , const char * argv[] )
{
    	//signal( SIGABRT , on_abort );
	
	std::cout << "Welcome Singnal 4G DTU\nInitializing...\n\tChecking configure file...";
    	if( access("/etc/dtu/config.xml" , F_OK ) == 0 ){// 检查配置文件是否存在
		// 读取配置文件
		std::shared_ptr< CSysVar > ptvar = GetOrCreateSysVar( "/etc/dtu/config.xml" );

		if( !ptvar ){
			std::cerr << TRED << "[ FAIL ]" << TNORMAL << "Bad configure file format , pls fix it." << std::endl;
			return -1 ;
		}
		std::cout << TGREEN << "[ OK ]" << TNORMAL << std::endl;

		bool en = false;
		ptvar->GetValue( "/firewall/enable" , en );
		if( access( "/etc/dtu/firewall.rules" , F_OK ) == 0 && en == true ){
			__show_line_1( "%s [ %d ] %s%s" , TGREEN , __LINE__ , TNORMAL , __PRETTY_FUNCTION__ );
			system( "iptables-restore < /etc/dtu/firewall.rules" );
		}else{
			system( "iptables -P FORWARD ACCEPT" );
			system( "iptables -F" );
		}
		// 启动DTU
		dtu * ptdtu = GetOrCreateDTU();
		if( ptdtu ){
			ptdtu->Run();
			while( true ){
				std::this_thread::yield();
				std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
			}

			delete ptdtu;
		}else{
			std::cerr << TRED << "Init DTU control fail." << TNORMAL << std::endl;
		}
	}else{
		std::cerr << TRED << "[ FAIL ]\n" << TNORMAL << "Missing config.xml. The file should be locate in /etc/dtu/config.xml" << std::endl;
	}

	return 0;
}
